#include "../server.hpp"
#include <fstream>
#include <regex>
#include <sys/stat.h>

std::unordered_map<int, std::string> _statu = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};
std::unordered_map<std::string, std::string> _mime = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};
const int DEFAULT_TIMEOUT = 10;
class Util
{
public:
    // 字符串分割
    static ssize_t Split(const std::string& src, const std::string& sep, std::vector<std::string>* array)
    {
        ssize_t offset = 0;
        while (offset < src.size())
        {
            int pos = src.find(sep, offset);
            // [offset, src.size())
            if (pos == std::string::npos)
            {
                if (offset == src.size())
                    break;
                array->push_back(src.substr(offset, src.size() - offset));
                return array->size();
            }
            // [offset, pos)[)[)
            if (pos - offset == 0)
            {
                offset = pos + sep.size();
                continue;
            }
            array->push_back(src.substr(offset, pos - offset));
            offset = pos + sep.size();
        }
        return array->size();
    }
    // 读取文件
    static bool ReadFile(std::string filename, std::string *buf)
    {
        std::ifstream ifs(filename, std::ios::binary);
        if (!ifs.is_open())
        {
            DBG_LOG("File Open Error: %s", filename.c_str());
            return false;
        }
       
        ifs.seekg(0, ifs.end);
        int length = ifs.tellg();
        ifs.seekg(0, ifs.beg);

        (*buf).resize(length);
        ifs.read(&(*buf)[0], length);
        if (!ifs.good())
        {
            DBG_LOG("Read File Error: %s", filename.c_str());
            ifs.close(); 
            return false;
        }

        ifs.close();
        return true;
    }
    // 写入文件
    static bool WriteFile(std::string filename, const std::string& buf)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (!ofs.is_open())
        {
            DBG_LOG("WriteFile Failed!: %s", filename.c_str());
            ofs.close();
            return false;
        }
        ofs.write(buf.c_str(), buf.size());
        ofs.close();
        return true;
    }
    // url编码, 避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中的特殊字符产生歧义
    // 编码格式： 将特殊字符的acsii值，转化为两个16进制字符，前缀% ==> C++ -> C%2B2B
    // 不编码的特殊字符：RFC3986 . - _ ~ 字母 数字
    // RFC3986文档规定，编码格式 %HH
    // W3C文档中规定，查询字符串中的空格，需要被转化为+
    static std::string UrlEncode(std::string url, bool convert_space_to_plus)
    {
        std::string ret;
        for (auto& e : ret)
        {
            if (e == '.' || e == '_' || e == '-' || e == '~' || isalnum(e))
            {
                ret += e;
                continue;
            }
            if (convert_space_to_plus == true && e == ' ')
            {
                ret += '+';
                continue;
            }

            char tmp[4];
            snprintf(tmp, 4, "%%%02x", e);
            ret += tmp;
        }
        return ret;
    }
    // url解码
    static char HexToI(char ch)
    {
        if (ch >= '0' && ch <= '9')
        {
            return ch - '0';
        }
        if (ch >= 'a' && ch <= 'z')
        {
            return ch - 'a' + 10;
        } 
        if (ch >= 'Z' && ch <= 'Z')
        {
            return ch - 'A' + 10;
        }
        return -1;
    }
    static std::string UrlDecode(std::string url, bool convert_space_to_plus)
    {
        std::string ret;
        for (int i = 0; i < url.size(); i++)
        {
            if (convert_space_to_plus == true && url[i] == '+')
            {
                ret += ' ';
                continue;
            }
            if (url[i] == '%')
            {
                char v1 = HexToI(url[++i]);
                char v2 = HexToI(url[++i]);

                ret += (v1 << 4) + v2;
                continue;
            }
            ret += url[i];
        }
        return ret;
    }
    // 响应状态码描述信息
    static std::string StatuDesc(int statu)
    {
        auto it = _statu.find(statu);
        if (it != _statu.end())
        {
            return it->second; 
        }
        return "Unknown";
    }
    // 根据文件后缀，获取文件mime
    static std::string ExtMime(std::string& filename)
    {
        int pos = filename.find_last_of('.');
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        std::string ext = filename.substr(pos);
        auto it = _mime.find(ext);
        if (it == _mime.end())
        {
            return "application/octet-stream";
        }

        return it->second;
    }
    // 判断一个文件是否是目录
    static bool IsDirectory(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }
    // 判断一个文件是否是普通文件
    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISREG(st.st_mode);
    }
    // http请求资源路径的有效性判断
    static bool VaildPath(const std::string& path)
    {
        std::vector<std::string> subdir;
        Split(path, "/", &subdir);
        int level = 0;
        for (auto& dir : subdir)
        {
            if (dir == "..")
            {
                level--;
                if (level < 0)
                    return false;
                continue;
            }
            level++;
        }
        return true;
    }
};


class HttpRequest {
    public:
        std::string _method;      //请求方法
        std::string _path;        //资源路径
        std::string _version;     //协议版本
        std::string _body;        //请求正文
        std::smatch _matches;     //资源路径的正则提取数据
        std::unordered_map<std::string, std::string> _headers;  //头部字段
        std::unordered_map<std::string, std::string> _params;   //查询字符串
    public:
        HttpRequest():_version("HTTP/1.1") {}
        void ReSet() 
        {
            _method.clear();
            _path.clear();
            _version = "HTTP/1.1";
            _body.clear();
            std::smatch match;
            _matches.swap(match);
            _headers.clear();
            _params.clear();
        }
        //插入头部字段
        void SetHeader(const std::string &key, const std::string &val)
        {
            _headers.insert(std::make_pair(key, val));
        }
        //判断是否存在指定头部字段
        bool HasHeader(const std::string &key) const 
        {
            auto it = _headers.find(key);
            if (it == _headers.end())
            {
                return false;
            }
            return true;
        }
        //获取指定头部字段的值
        std::string GetHeader(const std::string &key) const
        {
            if (HasHeader(key) == false)
                return "";
            auto it = _headers.find(key);
            return it->second;
        }
        //插入查询字符串
        void SetParam(const std::string &key, const std::string &val)
        {
            _params.insert(std::make_pair(key, val));
        }
        //判断是否有某个指定的查询字符串
        bool HasParam(const std::string &key) const 
        {
            auto it = _params.find(key);
            if (it == _params.end())
            {
                return false;
            }
            return true;
        }
        //获取指定的查询字符串
        std::string GetParam(const std::string &key) const 
        {
            if (HasParam(key) == false)
                return "";
            auto it = _params.find(key);
            return it->second;
        }
        //获取正文长度
        size_t ContentLength() const 
        {
            std::string str = GetHeader("Content-Length");
            if (str == "")
                return 0;
            return std::stol(str);
        }
        //判断是否是短链接
        bool Close() const 
        {
           // DBG_LOG("%d", HasHeader("Connection") == true);
          //  DBG_LOG("%d", GetHeader("Connection") == "keep-alive");
         //   DBG_LOG("[%s]", GetHeader("Connection").c_str());
            if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
                return false;
            return true;
        }
};


class HttpResponse
{
public:
    int _statu;
    bool _redirect_flag;
    std::string _body;        //请求正文
    std::string _redirect_url;
    std::unordered_map<std::string, std::string> _headers;  //头部字段
public:
    HttpResponse() :_statu(200) {}
    HttpResponse(int statu) :_statu(statu) {}
    void ReSet()
    {
        _statu = 0;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
    void SetHeader(const std::string &key, const std::string &val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    bool HasHeader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    std::string GetHeader(const std::string &key)
    {
        if (HasHeader(key) == false)
            return "";
        return _headers[key];
    }
    void SetContent(const std::string &body, const std::string &type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type", type);
    }
    void SetRedirect(const std::string &url, int statu = 302)
    {
        _redirect_flag = true; 
        _redirect_url = url;
        _statu = statu;
    }
    //判断是否是短链接
    bool Close()
    {
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};


const int MAX_LINE = 8092;
typedef enum 
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
}HttpRecvStatu;
class HttpContext
{
private:
    int _resp_statu; // 响应状态码
    HttpRecvStatu _recv_statu; // 当前接收解析信息的阶段状态
    HttpRequest _request; // 已经解析得到的请求信息

private:
    bool RecvHttpLine(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_LINE) return false;
        // 带有末尾的换行 
        std::string line = buf->GetLine();
        // 不足一行
        if (line.size() == 0)
        {
            if (buf->ReadAbleSize() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;
                return false;
            }
            return true;
        }
        if (line.size() > MAX_LINE)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414;
            return false;
        }

        if (ParseHttpLine(line) == false)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414;
            return false;
        }
        buf->MoveReadOffset(line.size());

        // 请求行处理完毕，接下来是请求报头
        _recv_statu = RECV_HTTP_HEAD;
        _resp_statu = 200;
        return true;
    }
    bool ParseHttpLine(std::string line)
    {
        std::smatch matches;
        std::regex reg("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
        bool ret = std::regex_match(line, matches, reg);

        if (ret == false)
        {
            _resp_statu = 400;
            _recv_statu = RECV_HTTP_ERROR;
            return false;
        }

        _request._method = matches[1];
        // 将_request中全部转化成大写字符
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        _request._path = Util::UrlDecode(matches[2], false);
        _request._version = matches[4];
        std::string query = matches[3];
        std::vector<std::string> query_array;
        Util::Split(query, "&", &query_array);

        for (auto& e : query_array)
        {
            int pos = e.find("=");
            if (pos == std::string::npos)
            {
                _resp_statu = 400;
                _recv_statu = RECV_HTTP_ERROR;
                return false;
            }
            std::string str1 = Util::UrlDecode(e.substr(0, pos), false);
            std::string str2 = Util::UrlDecode(e.substr(pos + 1), false);
            _request.SetParam(str1, str2);
        }
        return true;
    }
    bool RecvHttpHead(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_HEAD) return false;

        while (1)
        {
            /* 注意 */
            std::string line = buf->GetLineAndPop();
            // 不足一行
            if (line.size() == 0)
            {
                if (buf->ReadAbleSize() > MAX_LINE)
                {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414;
                    return false;
                }
                return true;
            }
            if (line.size() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;
                return false;
            }
            if (line == "\r\n" || line == "\n")
                break;
            if (ParseHttpHead(line) == false)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;
                return false;
            }
        }

        // 头部处理完毕，进入正文
        _recv_statu = RECV_HTTP_BODY;
        _resp_statu = 200;
        return true;
    }
    bool ParseHttpHead(std::string line)
    {
        if (line.back() == '\n') line.pop_back();
        if (line.back() == '\r') line.pop_back();
        ssize_t pos = line.find(": ");
        if (std::string::npos == pos)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;
            return false;
        }
        std::string str1 = Util::UrlDecode(line.substr(0, pos), false);
        std::string str2 = Util::UrlDecode(line.substr(pos + 2), false);

        _request.SetHeader(str1, str2);
        return true;
    }
    bool RecvHttpBody(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_BODY) return false;
        // 获取正文长度
        int content_length = _request.ContentLength();
        if (content_length == 0)
        {
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        // 当前获取了多少正文，就是往 _request._body 中放了多少数据
        int real_length = content_length - _request._body.size();
        // 接收正文，要考虑当前缓冲区的数据是否是全部正文
        if (buf->ReadAbleSize() >= real_length)
        {
            _request._body += buf->ReadAsString(real_length);
            buf->MoveReadOffset(real_length);
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        _request._body += buf->ReadAsString(buf->ReadAbleSize());
        buf->MoveReadOffset(buf->ReadAbleSize());
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }

public:
    HttpContext() 
        :_resp_statu(200)
        ,_recv_statu(RECV_HTTP_LINE)
    {}
    ~HttpContext() {}

    int RespStatu()
    {
        return _resp_statu;
    }
    HttpRecvStatu RecvStatu()
    {
        return _recv_statu;
    }
    HttpRequest& Request()
    {
        return _request;
    }
    void Reset()
    {
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;   
        _request.ReSet();
    }
    void RecvHttpRequest(Buffer *buf) // 接收并解析Http请求   
    {
        int a = 0;
        switch(_recv_statu)
        {
            case RECV_HTTP_LINE: RecvHttpLine(buf);
            case RECV_HTTP_HEAD: RecvHttpHead(buf);
            case RECV_HTTP_BODY: RecvHttpBody(buf);
        }
        return;
    } 
};


class HttpServer
{
private:
    using Handler = std::function<void(const HttpRequest&, HttpResponse *)>;
    // 这里直接存储regex，正则表达式对象，提前进行编译，在进行查找的时候，就不需要进行编译了，提高效率
    using Handlers = std::vector<std::pair<std::regex, Handler>>;
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;

    std::string _basedir; // 静态资源路径
    TcpServer _server;

private:
    void WriteResponse(const PtrConnection& conn, const HttpRequest& req, HttpResponse& rsp) // 将HttpResponse中要素按照http协议格式进行组织发送
    {
        //1. 先完善头部字段
        if (req.Close() == true)
        {
            rsp.SetHeader("Connection", "close");
        }
        else 
        {
            rsp.SetHeader("Connection", "keep-alive");
        }
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Length")== false) 
            rsp.SetHeader("Content-Length",std::to_string(rsp._body.size()));
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Type") == false)
            rsp.SetHeader("Content-Type", "application/octet-stream");
        if (rsp._redirect_flag == true) 
            rsp.SetHeader("Location", rsp._redirect_url);
        //2. 将rsp中的要素，按照http协议格式进⾏组织
        std::stringstream rsp_str;
        rsp_str << req._version << " " << std::to_string(rsp._statu) << " "<< Util::StatuDesc(rsp._statu) << "\r\n";
        for (auto &head : rsp._headers) 
            rsp_str << head.first << ": " << head.second << "\r\n";
        rsp_str << "\r\n";
        rsp_str << rsp._body;
        //3. 发送数据
        conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
    }
    bool IsFileHandler(const HttpRequest& req) //  判断一个请求是否是静态资源请求
    {
        // 必须设置了静态根目录
        if (_basedir.empty())
            return false;
        // 请求方法必须是GET， HEAD请求方法
        if ((req._method == "GET" || req._method == "HEAD") == false)
            return false;
        // 请求资源路径必须是合法的
        if (Util::VaildPath(req._path) == false)
            return false;
        // 请求的资源必须存在
        //     有一个请求比较特殊，纯粹的相对根目录 / ：这种情况给后面默认添加一个index.html
        std::string req_path = _basedir + req._path;
        if (req._path.back() == '/')
            req_path += "index.html";
        if (Util::IsRegular(req_path) == false)
            return false;
        
        return true;
    }
    // 静态资源的请求服务 --- 将静态资源文件的数据读出来，放到body中，并设置mime
    void FileHandler(const HttpRequest& req, HttpResponse& resp) 
    {
        std::string req_path = _basedir + req._path;
        if (req._path.back() == '/')
            req_path += "index.html";

        bool ret = Util::ReadFile(req_path, &resp._body);
        if (ret == false)
            return;
        std::string mime = Util::ExtMime(req_path);
        resp.SetHeader("Content-Type", mime);
        return;
    }
    void Dispatchar(HttpRequest& req, HttpResponse& resp, Handlers& handlers) // 功能性请求的分类处理
    {
        // 在对应请求方法的路由表中，查找是否有对应资源的处理函数，有则调用，否则405
        // 思想：路由表中存储的是键值对，处理函数 & 正则表达式
        // /numbers/(\d+)      /numbers/12345
        for (auto& handler : handlers)
        {
            const std::regex& re = handler.first;
            const Handler& functor = handler.second;
            bool ret = std::regex_match(req._path, req._matches, re);
            if (ret == false)
                continue;
            return functor(req, &resp);
        }
        resp._statu = 404; 
        return;
    }
    void Route(HttpRequest& req, HttpResponse* resp)
    {
        // 1、对请求进行分辨，是一个静态资源请求还是一个功能性资源请求  
        // 既不是静态资源请求也不是功能性资源请求，返回404
        if (IsFileHandler(req) == true)
        {
            // 静态资源请求，进行静态资源请求处理
            return FileHandler(req, *resp);
        }
        if (req._method == "GET" || req._method == "HEAD")
            return Dispatchar(req, *resp, _get_route);
        else if (req._method == "POST")
            return Dispatchar(req, *resp, _post_route);  
        else if (req._method == "PUT")
            return Dispatchar(req, *resp, _put_route);
        else if (req._method == "DELETE")
            return Dispatchar(req, *resp, _delete_route);
        
        resp->_statu = 405;
        return;
    }
    void ErrorHandler(const HttpRequest& req, HttpResponse* resp)
    {
        // 组织错误页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type'content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(resp->_statu);
        body += " ";
        body += Util::StatuDesc(resp->_statu);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        //2. 将⻚⾯数据，当作响应正⽂，放⼊rsp中
        resp->SetContent(body, "text/html");
    }
    void OnMessage(const PtrConnection& conn, Buffer *buf) // 缓冲区数据解析+处理
    {
        while (buf->ReadAbleSize() > 0)
        {
            DBG_LOG("OnMessage");
            // 1、获取上下文
            HttpContext *context = conn->GetContext()->Get<HttpContext>();
            // std::cout << "[" << buf->ReaderPosition() << "]" << std::endl;
            // 2、通过上下文数据对缓冲区数据进行解析，得到request对象
            //     如果缓冲区数据解析错误，直接返回出错响应
            //     如果解析正常，且请求已经获取完毕，处理
            context->RecvHttpRequest(buf);
            HttpRequest& request = context->Request();
            HttpResponse response(context->RespStatu());
            if (context->RespStatu() >= 400)
            {
                // 进行错误响应，关闭连接
                ErrorHandler(request , &response); // 填充一个错误显示页面数据到rsp中
                WriteResponse(conn, request, response); // 组织响应发送给客户端
                context->Reset(); // 重置正文信息
                buf->MoveReadOffset(buf->ReadAbleSize());//出错了就把缓冲区数据清空
                
                conn->Shutdown();
                return;
            }
            if (context->RecvStatu() != RECV_HTTP_OVER)
            {
                // 当前请求还没接收完整，等待新数据到来
                return;
            }
            // 3、请求路由
            Route(request, &response);
            // 4、对HttpResponse进行组织发送
            DBG_LOG("%s", response._body.c_str());
            WriteResponse(conn, request, response);
            // 5、重置上下文
            context->Reset();
            // 6、根据长短连接判断是否继续处理或者关闭连接
            if (response.Close() == true) 
            {
                DBG_LOG("response.Close()");
                conn->Shutdown();
            }
        }
        return;
    }
    void OnConnected(const PtrConnection& conn) // 设置上下文
    {
        conn->SetContext(HttpContext());
        DBG_LOG("New Connection: %p", conn.get());
    }
public:
    HttpServer(int port, int timeout = DEFAULT_TIMEOUT) 
        :_server(port)
    {   
        DBG_LOG("启动超时销毁：%d", timeout);
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    ~HttpServer() {}

    void SetBaseDir(std::string basedir)
    {
        bool ret = Util::IsDirectory(basedir);
        assert(ret == true);
        _basedir = basedir;
    }
    // 设置/添加，请求(正则表达式)与处理函数的映射关系
    void Get(const std::string& pattern, const Handler& handler)
    {
        return _get_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Post(const std::string& pattern, const Handler& handler)
    {
        return _post_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Put(const std::string& pattern, const Handler& handler)
    {
        return _put_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Delete(const std::string& pattern, const Handler& handler)
    {
        return _delete_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void SetThreadCount(int count)
    {
        return _server.SetThreadCount(count);
    }
    void Listen()
    {
       return _server.Start();
    }
};